/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.allerj.task;

import com.asprise.util.jtwain.JTwainException;
import com.asprise.util.jtwain.Source;
import com.asprise.util.jtwain.SourceManager;
import it.allerj.analysis.TestAnalysis;
import it.allerj.gui.MainJFrame;
import it.allerj.gui.component.MyProgressBar;
import it.allerj.model.AllergicTest;
import it.allerj.model.AllergicTestDoubleFrame;
import it.allerj.model.AllergicTestSingleFrame;
import it.allerj.model.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author Alessandro Veracchi
 */
public class ScanFrameTask extends SwingWorker<Void, Void> {

    private java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("it/allerj/bundle/allerj");
    private JButton actionButton;
    private JButton forward;
    private JLabel result;
    private JLabel titleStep;
    private String endText;
    private MainJFrame mainJFrame;
    private Source source;
    private BufferedImage image;
    private static final String SCANNAME = "Q-Scan Mini Flatbed V1.1"; 

    public ScanFrameTask(JButton actionButton, MainJFrame mainJFrame, JButton forward, JLabel result, String endText, JLabel titleStep) {
        super();
       
            this.actionButton = actionButton;
            this.forward = forward;
            this.result = result;
            this.endText = endText;
            this.mainJFrame = mainJFrame;
         this.titleStep =titleStep;


    }

    private ScanFrameTask() {
    }

    @Override
    public Void doInBackground() {

           
     try {
            //this.source = SourceManager.instance().selectSourceUI(); //
         this.source = SourceManager.instance().selectSourceByName(SCANNAME);
             if (source == null) {
                System.err.println("There is no (default) source on the system!");
                return null;
            }

            source.open();
            image = source.acquireImageAsBufferedImage();
            
            source.close();
        } catch (Exception ex) {
            Logger.getLogger(ScanFrameTask.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            SourceManager.closeSourceManager();
        }

        /*
        Random random = new Random();
        int progress = 0;
        //Initialize progress property.
        setProgress(0);
        while (progress < 100) {
        //Sleep for up to one second.
        try {
        Thread.sleep(random.nextInt(100));
        } catch (InterruptedException ignore) {}
        //Make random progress.
        progress += random.nextInt(10);
        setProgress(Math.min(progress, 100));
        }
         */
        return null;
    }

    /*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {

        if (forward != null && result != null && mainJFrame != null && mainJFrame.getAllergicTest() != null) {
            mainJFrame.setCursor(null); //turn off the wait cursor
            forward.setEnabled(true);
            //actionButton.setEnabled(true);
            //mainJFrame.getAllergicTest().getFrameList().add(new Frame());
            
           /* Kernel kernel = new Kernel(3, 3,
                new float[] { // sharpening filter kernel
                        0.f, -1.f,  0.f,
                       -1.f,  5.f, -1.f,
                        0.f, -1.f,  0.f
                    });
            
            i
            BufferedImageOp op = new ConvolveOp(kernel);
            image = op.filter(image, null);*/
            if(image==null){
                result.setText(bundle.getString("i18n.frame.not.acquired"));
                 int n = JOptionPane.showOptionDialog(
                mainJFrame,
                java.util.ResourceBundle.getBundle("it/allerj/bundle/allerj").getString("i18n.Would.you.try.scan.again"),
                java.util.ResourceBundle.getBundle("it/allerj/bundle/allerj").getString("i18n.Confirm"),
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,     //do not use a custom Icon
                MainJFrame.defaultOptions,  //the titles of buttons
                MainJFrame.defaultOptions[0]);
                if(n==0){
                     mainJFrame.startScanProcedure();
                    //TODO REMOVE THIS
                    //AllergicTest allergicTest = mainJFrame.getAllergicTest();
                    //allergicTest.initEmptyAllergicTest();
                   
                    //mainJFrame.setAllergicTest(allergicTest);
                } else {
                    mainJFrame.resetView();
                }
                
                 
            }
            if(mainJFrame.getAllergicTest() instanceof AllergicTestDoubleFrame && mainJFrame.getImage()!=null){
                mainJFrame.setImage2(image);
            } else mainJFrame.setImage(image);
            
           
            if (mainJFrame.getImage()!=null && mainJFrame.getAllergicTest() instanceof AllergicTestSingleFrame) {
                 result.setText(bundle.getString("i18n.frame.acquired"));
                if (endText != null || endText.trim().length() > 0) {
                    forward.setText(endText);
                }
                forward.setActionCommand("save");
                forward.setEnabled(true);
            } else if(mainJFrame.getImage2()==null && mainJFrame.getAllergicTest() instanceof AllergicTestDoubleFrame){
                result.setText(bundle.getString("i18n.frame.acquired.acquire.second"));
                mainJFrame.setNumberFrame(2);
                titleStep.setText(2+bundle.getString("'_")+bundle.getString("i18n.scan.frame"));
                forward.setEnabled(false);
                actionButton.setEnabled(true);
                mainJFrame.pack();
                mainJFrame.repaint();
            } else {
                if (endText != null || endText.trim().length() > 0) {
                    forward.setText(endText);
                }
                forward.setActionCommand("save");
                forward.setEnabled(true);
            }
            
        }
    }


    public JFrame getMainJFrame() {
        return mainJFrame;
    }
}
